<template>
  <div>
    <!-- 面包屑导航 -->
    <Bread></Bread>
    <!-- 卡片区域 -->
    <el-card class="box-card">
      <!-- 搜索框 -->
      <el-input
        placeholder="请输入内容"
        v-model="input"
        clearable
        class="input"
      >
        <template slot="append">
          <span class="el-icon-search" @click="userSeach"></span>
        </template>
      </el-input>
      <el-button type="primary" class="user" @click="addUser"
        >添加用户</el-button
      >
      <!-- 用户列表 -->
      <el-table :data="tableData" border style="width: 100%" class="table">
        <el-table-column type="index" width="100px" label="#">
        </el-table-column>
        <el-table-column prop="username" label="姓名"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="userEdit(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editState(scope.row.id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="delUser(scope.row.id)"
            ></el-button>
            <!-- 分配权限按钮 -->
            <el-tooltip
              effect="dark"
              content="分配权限"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="distribution(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.pagenum"
          :page-sizes="[1, 2, 5, 10]"
          :page-size="queryInfo.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
      <!-- 添加弹出框 -->
      <el-dialog :visible.sync="addDialogVisible" width="30%">
        <el-form
          :model="addForm"
          :rules="addFormRules"
          ref="addFormRef"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="mobile">
            <el-input v-model="addForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitUser">提交</el-button>
          <el-button @click="addDialogVisible = false">取消</el-button>
        </span>
      </el-dialog>
      <!-- 修改弹出框 -->
      <el-dialog :visible.sync="dialogVisible" width="30%">
        <el-form
          :model="editForm"
          :rules="editFormRules"
          ref="editRuleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="用户名">
            <el-input v-model="editForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="editForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="editUser">确定</el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </span>
      </el-dialog>
      <!-- 分配权限弹出框 -->
      <el-dialog
        title="分配角色 "
        :visible.sync="roleDialogVisible"
        width="50%"
      >
        <div>
          <p>当前的用户:{{ userInfo.username }}</p>
          <p>当前的角色:{{ userInfo.role_name }}</p>
          <p>
            分配新角色：
            <el-select v-model="selectedRole" placeholder="请选择">
              <el-option
                v-for="item in roleList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
              ></el-option>
            </el-select>
          </p>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="roleDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="updataRole()">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import Bread from "../bread.vue";
import userAPI from "../../http/API/Users";
export default {
  components: {
    Bread,
  },
  data() {
    //验证邮箱的正则
    var checkEmail = (rule, value, callback) => {
      //alert(value)
      var reg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
      if (reg.test(value)) {
        // 格式正确返回true
        callback();
      } else {
        // 格式不正确
        return callback(new Error("邮箱格式不对"));
      }
    };
    //验证手机号的正则
    var checkMobile = (rule, value, callback) => {
      var mobileReg = /^1[3456789]\d{9}$/;
      if (mobileReg.test(value)) {
        // 格式正确返回true
        callback();
      } else {
        // 格式不正确
        return callback(new Error("手机号格式不对"));
      }
    };
    return {
      input: "",
      tableData: [],
      //获取用户列表的参数
      queryInfo: {
        query: "",
        pagenum: 1, //当前页数
        pagesize: 10, //当前每页显示多少数据
      },
      total: 0,
      addDialogVisible: false, //添加弹出框
      //添加 验证
      addFormRules: {
        username: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
          { min: 6, max: 15, message: "长度在6 到 15 个字符", trigger: "blur" },
        ],
        email: [
          { required: true, message: "请输入邮箱地址", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入电话号码", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      dialogVisible: false, //编辑弹出框
      //验证 修改
      editFormRules: {
        email: [
          { required: true, message: "请输入邮箱地址", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入电话号码", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
      editForm: {},
      //需要被分配的用户信息
      userInfo: {},
      selectedRole: "",
      //角色列表
      roleList: [],
      roleDialogVisible: false,
    };
  },
  created() {
    this.getTableData();
  },
  methods: {
    //用户列表
    getTableData() {
      userAPI.getUserList(this.queryInfo).then((res) => {
        // console.log(res);
        if (res.data.meta.status !== 200) {
          this.$message.error(res.data.meta.msg);
        } else {
          this.$message.success(res.data.meta.msg);
          this.tableData = res.data.data.users;
          this.total = res.data.data.total;
        }
      });
    },
    handleSizeChange(val) {
      this.queryInfo.pagesize = val;
      // console.log(`每页 ${val} 条`);
      this.getTableData();
    },
    handleCurrentChange(val) {
      this.queryInfo.pagenum = val;
      // console.log(`当前页: ${val}`);
      this.getTableData();
    },
    //状态改变
    userEdit(stateChange) {
      // console.log(stateChange);
      userAPI
        .editUserState(stateChange.id, stateChange.mg_state)
        .then((res) => {
          // console.log(res);
          if (res.data.meta.status == 200) {
            this.$message.success("更新用户状态成功");
          } else {
            this.$message.error("更新用户状态失败");
          }
        });
    },
    //搜索
    userSeach() {
      this.queryInfo.query = this.input;
      this.getTableData();
    },
    //添加用户
    addUser() {
      this.addDialogVisible = true;
    },
    submitUser() {
      userAPI.addUser(this.addForm).then((res) => {
        // console.log(res)
        if (res.data.meta.status == 201) {
          this.$message.success("创建用户成功");
        } else {
          this.$message.error("创建用户失败");
        }
        this.addDialogVisible = false;
        this.getTableData();
        this.username = "";
        this.password = "";
        this.email = "";
        this.mobile = "";
      });
    },
    //显示编辑对话框
    editState(id) {
      userAPI.editState(id).then((res) => {
        console.log(res);
        this.editForm = res.data.data;
      });
      this.dialogVisible = true;
    },
    //编辑用户
    editUser() {
      this.$refs.editRuleForm.validate((valid) => {
        if (valid) {
          userAPI
            .editUsers(id, {
              email: this.editForm.email,
              mobile: this.editForm.mobile,
            })
            .then((res) => {
              console.log(res);
              if (res.data.meta.status == 200) {
                this.$message.success("编辑用户成功");
              } else {
                this.$message.error("编辑用户失败");
              }
              this.dialogVisible = false;
              this.getTableData();
            });
        }
      });
    },
    //删除用户
    delUser(id) {
      userAPI.deletUser(id).then((res) => {
        console.log(res);
        if (res.data.meta.status == 200) {
          this.$message.success("用户删除成功");
        } else {
          this.$message.error("用户删除失败");
        }
        this.getTableData();
      });
    },
    //分配权限
    distribution(userInfo) {
      this.userInfo = userInfo;
      this.roleDialogVisible = true;
      this.$http.get("roles").then((res) => {
        console.log(res);
        this.roleList = res.data.data;
      });
    },
    //确定角色分配权限
    updataRole() {
      this.roleDialogVisible = false;
      if (this.selectedRole == "") {
        this.$message.error("请选择要分配的新角色");
      } else {
        userAPI
          .updataRoles(this.userInfo.id, {
            rid: this.selectedRole,
          })
          .then((res) => {
            console.log(res);
            if (res.data.meta.status == 200) {
              this.$message.success("设置角色成功");
            } else {
              this.$message.error("设置角色失败");
            }
          });
        this.selectedRole = "";
        this.getTableData();
      }
    },
  },
};
</script>

<style >
.breadcrumb {
  margin-bottom: 20px;
}
.input {
  width: 500px;
}
.user {
  margin-left: 10px;
}
.table {
  margin-top: 20px;
}
.block {
  margin-top: 20px;
}
</style>
